//
//  YSGSetupNameViewController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/11/18.
//  Copyright © 2020 QDSG. All rights reserved.
//

import UIKit

class YSGSetupNameViewController: BaseViewController {
    
    var handleClosure: ((String) -> Void)?
    
    @IBOutlet private weak var textField: UITextField! {
        didSet {
            textField.placeholder = "请输入姓名"
            textField.font = .medium(16)
            textField.textColor = .textDark
            textField.clearButtonMode = .whileEditing
            textField.returnKeyType = .done
        }
    }
    
    private var name: String
    
    private var currentName: String
    
    init(name: String) {
        self.name = name
        self.currentName = name
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var leftBtn: UIButton = {
        let button = createButton(self, action: #selector(cancelEdit), title: "取消")
        button.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
        return button
    }()
    
    private lazy var rightBtn: UIButton = {
        let button = createButton(self, action: #selector(sureEdit), title: "完成", isEnable: false)
        button.frame = CGRect(x: 0, y: 0, width: 60, height: 40)
        return button
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "设置姓名"
        
        let leftItem = UIBarButtonItem(customView: leftBtn)
        navigationItem.leftBarButtonItem = leftItem
        
        let rightItem = UIBarButtonItem(customView: rightBtn)
        navigationItem.rightBarButtonItem = rightItem
        rightBtn.isEnabled = false
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {
            self.rightBtn.isEnabled = true
        })
        
        textField.text = name
        textField.becomeFirstResponder()
        textField.addTarget(self, action: #selector(textFieldEditingChanged(_:)), for: .editingChanged)
    }
    
    // MARK: - Action
    @objc private func cancelEdit() {
        view.endEditing(true)
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func sureEdit() {
        view.endEditing(true)
        if name.isEmpty {
            AlertTool.showAlert(self, title: "没有输入姓名，请重新填写", sureTitle: "我知道了")
            return
        }
        
        HUDTool.showActivity()
        ProfileViewModel.changeNickname(nickname: name) { (message, code) in
            HUDTool.hideActivity()
            switch code {
            case .failure:
                HUDTool.showError(message: message)
            case .success:
                HUDTool.show(in: mainWindow, message: "修改成功", position: .center)
                self.handleClosure?(self.name)
                self.dismiss(animated: true, completion: nil)
            }
        }
    }
    
    @objc private func textFieldEditingChanged(_ textField: UITextField) {
        YSGLog(textField.text)
        name = textField.text!
        
        rightBtn.isEnabled = currentName != name
    }
    
    // MARK: - Helpers
    private func createButton(_ target: Any?,
                              action: Selector,
                              title: String?,
                              isEnable: Bool = true) -> UIButton
    {
        let btn = UIButton(type: .custom)
        btn.titleLabel?.font = .medium_14
        btn.setTitle(title, for: .normal)
        btn.setTitleColor(.textGray, for: .normal)
        btn.addTarget(target, action: action, for: .touchUpInside)
        
        btn.layer.cornerRadius = 10
        btn.clipsToBounds = true
        
        if !isEnable {
            btn.setTitleColor(.white, for: .normal)
            btn.setTitleColor(.textLight, for: .highlighted)
            btn.setTitleColor(.textLight, for: .disabled)
            btn.setBackgroundImage(UIImage(color: .mainLight), for: .disabled)
            btn.setBackgroundImage(UIImage(color: .mainColor), for: .normal)
        }
        
        return btn
    }
}
